<template>
	<view class="content">
		<g-watermark />
		<view class="content_form">
			<u-form :model="formData" ref="form" :label-width="120" label-align="left">
				<u-form-item label="收件人" prop="userRealName" required v-if="current==0">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(0)">选择</text>
						<text @click="handleCS"
							style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送' }}</text>
						<!-- <text @click="handleMS"
							style="color:#0960bd;margin-left: 20rpx;">{{ isms ? '删除密送' : '添加密送' }}</text> -->
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers']"
								:key="item.key" @close="handleCloseTag(index,0)" closeable />
						</view>
					</view>
				</u-form-item>
				<template v-if="current==1">
					<u-form-item label="部门" prop="userRealName" required>
						<view style="width: 100%;">
							<text style="color:#0960bd" @click="handleTkiTreeDepart()">选择</text>
							<text @click="handleCS"
								style="color:#0960bd;margin-left: 20rpx;">{{ iscs ? '删除抄送' : '添加抄送' }}</text>
							<!-- <text @click="handleMS"
								style="color:#0960bd;margin-left: 20rpx;">{{ isms ? '删除密送' : '添加密送' }}</text> -->
							<view
								style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
								<u-tag :text="item.name" mode="light" v-for="(item,index) in formData['hadDeptList']"
									:key="item.code" @close="handleCloseTag(index,3)" closeable />
							</view>
						</view>
					</u-form-item>
				</template>
				<u-form-item label="抄送" v-if="iscs">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(1)">选择</text>
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers1']"
								:key="item.key" @close="handleCloseTag(index,1)" closeable />
						</view>
					</view>
				</u-form-item>
				<!-- 	<u-form-item label="密送" v-if="isms">
					<view style="width: 100%;">
						<text style="color:#0960bd" @click="handleSelectUser(2)">选择</text>
						<view
							style="width:100%;max-height: 150upx;overflow-y: auto;display: flex;gap: 10upx;flex-wrap: wrap;">
							<u-tag :text="item.title" mode="light" v-for="(item,index) in formData['hadUsers2']"
								:key="item.key" @close="handleCloseTag(index,2)" closeable />
						</view>
					</view>
				</u-form-item> -->
				<u-form-item label="主题" prop="title" required>
					<uni-easyinput v-model="formData.title" placeholder="请填写主题"></uni-easyinput>
				</u-form-item>
				<LEditor v-model="formData.content" ref="lEditorRef" />
				<u-form-item label="附件">
					<FileUpload ref="fileUploadRef" :msgId="formData.id" />
				</u-form-item>
				<template v-if="ishj">
					<u-form-item label="发送时间" prop="send_now" required>
						<u-radio-group v-model="formData.send_now" style="width: 100%;">
							<u-radio :name="'yes'" :wrap="true">
								立即发送
							</u-radio>
							<u-radio :name="'no'" :wrap="true">
								<view style="display: flex;gap:10rpx;align-items: center;">
									定时发送 <u-input disabled v-model="formData.send_time" placeholder="请选择时间" />
									<u-icon name="arrow-down" @click="showTime=true"></u-icon>
								</view>
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="回执" prop="receipt_state" required>
						<u-radio-group v-model="formData.receipt_state">
							<u-radio v-for="(item, index) in receipt_stateList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item label="等级" prop="msg_level" required>
						<u-radio-group v-model="formData.msg_level">
							<u-radio v-for="(item, index) in msg_levelList" :key="index" :name="item.value">
								{{item.label}}
							</u-radio>
						</u-radio-group>
					</u-form-item>
				</template>
			</u-form>
		</view>

		<view class="body_bottom">
			<view @click="handleRefresh">
				刷新
			</view>
			<view @click="handleSave" v-if="type == 'draftbox'">
				保存
			</view>
			<view @click="handleSend" v-if="type == 'draftbox'">
				发送
			</view>
			<view @click="handleResetSend" v-if="type == 'outbox'">
				重新发送
			</view>
			<view @click="handleWithdraw" v-if="type == 'outbox'">
				撤回
			</view>
		</view>
		<MxDatepicker format="yyyy-mm-dd hh:ii" type="datetime" :show="showTime" :value="times" :show-tips="true"
			:show-seconds="false" @confirm="handleConfirmTime" @cancel="showTime=false" />
		<SelectUser ref="selectUserRef" @confirm="handleSelectUserConfirm" />
		<TkiTree idKey="code" rangeKey="name" :range="departmentList" ref="tkiTreeDepartRef"
			@confirm="handleTkiTreeDepartConfirm" :multiple="true" />
	</view>
</template>

<script>
	import {
		postFormAction,
	} from '@/utils/request.js';
	import {
		msg_levelList,
		receipt_stateList
	} from './writebox.js'
	import MxDatepicker from '../../component/mx-datepicker/mx-datepicker'
	import SelectUser from '@/components/selectUser/index.vue'
	import LEditor from '../../component/l-editor/l-editor.vue'
	import TkiTree from '@/components/tki-tree/tki-tree.vue'
	import FileUpload from '../../component/file-upload/file-upload.vue'
	import {
		mapState
	} from "vuex";
	export default {
		components: {
			MxDatepicker,
			SelectUser,
			LEditor,
			TkiTree,
			FileUpload
		},
		data() {
			return {
				msg_levelList,
				receipt_stateList,
				formData: {
					userRealName: "",
					userRealName1: "",
					userRealName2: "",
					title: "",
					content: "",
				},
				rules: {
					userRealName: [{
						required: true,
						message: '收件人不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					title: [{
						required: true,
						message: '主题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					// content: [{
					// 	required: true,
					// 	message: '正文不能为空',
					// 	// 可以单个或者同时写两个触发验证方式 
					// 	trigger: ['change', 'blur'],
					// }],
				},
				userType: 0, //0是收件人 1是抄送 2是加密
				url: {
					editDraftPage: '/message_oa/editDraftPage',
					updateDraft: '/message_oa/updateDraft',
					transmit: '/message_oa/transmit',
					recall: '/message_oa/recall',
				},
				ishj: false, //是否高级功能
				iscs: false, //抄送
				isms: false, //密送
				times: null,
				type: '',
				mainId: '',
				showTime: false,
				departmentList: [],
				current: 0, //0发送人 1部门
			}
		},
		onLoad(options) {
			this.type = options.type || ''
			this.mainId = options.mainId || ''
			this.getDepartmentsData()
			this.init()
		},
		computed: {
			...mapState(["emailType"]),
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		methods: {
			init() {
				this.$nextTick(() => {
					setTimeout(async () => {
						try {
							this.$refs.form.resetFields()
							if (this.type == 'outbox') {
								this.ishj = false;
							} else {
								this.ishj = true;
							}
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							const result = await postFormAction(this.url.editDraftPage, {
								id: this.mainId
							});
							const res = result.data
							this.formData = {
								...res,
								receipt_state: res.receiptState,
								msg_level: res.msgLevel,
								send_now: res.isSent == 1 ? 'yes' : 'no',
								isToOutBox: res.isToOutBox ? 'true' : 'false',
								userRealName: res.realNameJs,
								userRealName1: res.realNameCs,
								userRealName2: res.realNameMs,
								receiver: res.receiversjs,
								receiver1: res.receiverscs,
								receiver2: res.receiversms,
								send_time: res.sendTime,
							};

							if (this.$refs.fileUploadRef) {
								this.$refs.fileUploadRef.fileList = res.attachments || []
							}
							this.formData.hadUsers = []
							this.formData.hadUsers1 = []
							this.formData.hadUsers2 = []
							this.formData.hadDeptList = []
							if (this.formData.receiver) {
								const receivers = this.formData.receiver.split(',')
								const userRealNames = this.formData.userRealName.split(',')
								if (this.formData.receiver.indexOf('dept@') != -1) {
									this.current = 1
									userRealNames.forEach((item, index) => {
										this.formData.hadDeptList.push({
											code: receivers[index].replace('dept@',
												''),
											name: item,
										})
									})
								} else {
									this.current = 0
									userRealNames.forEach((item, index) => {
										this.formData.hadUsers.push({
											key: receivers[index],
											name: receivers[index],
											title: item,
											realName: item,
										})
									})
								}
							}
							if (this.formData.receiver1) {
								this.iscs = true;
								const receivers1 = this.formData.receiver1.split(',')
								const userRealNames1 = this.formData.userRealName1.split(',')
								userRealNames1.forEach((item, index) => {
									this.formData.hadUsers1.push({
										key: receivers1[index],
										name: receivers1[index],
										title: item,
										realName: item,
									})
								})
							} else {
								this.iscs = false;
							}
							if (this.formData.receiver2) {
								this.isms = true;
								const receivers2 = this.formData.receiver2.split(',')
								const userRealNames2 = this.formData.userRealName2.split(',')
								userRealNames2.forEach((item, index) => {
									this.formData.hadUsers2.push({
										key: receivers2[index],
										name: receivers2[index],
										title: item,
										realName: item,
									})
								})
							} else {
								this.isms = false;
							}
							console.log("formData=>", this.formData)
							uni.hideLoading()
						} catch (e) {
							console.log("e", e)
							uni.hideLoading()
						}
					}, 10)
				});
			},
			handleCS() {
				this.iscs = !this.iscs;
				if (!this.iscs) {
					this.formData.userRealName1 = '';
					this.formData.receiver1 = '';
					this.formData.hadUsers1 = []
				}
			},
			handleMS() {
				this.isms = !this.isms;
				if (!this.isms) {
					this.formData.userRealName2 = '';
					this.formData.receiver2 = '';
					this.formData.hadUsers2 = []
				}
			},

			//选择人员
			handleSelectUser(type) {
				this.userType = type
				switch (this.userType) {
					case 0:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers']
						})
						break;
					case 1:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers1']
						})
						break;
					case 2:
						this.$refs.selectUserRef.open({
							users: this.formData['hadUsers2']
						})
						break;
				}
			},
			//选择用户回调
			handleSelectUserConfirm({
				selectUserList,
				label,
				value
			}) {
				console.log("handleSelectUserConfirm", selectUserList)
				switch (this.userType) {
					case 0:
						this.formData.userRealName = label
						this.formData.receiver = value
						if (Array.isArray(this.formData['hadUsers'])) {
							this.formData['hadUsers'] = this.formData['hadUsers'].concat(selectUserList)
						} else {
							this.formData['hadUsers'] = selectUserList
						}
						this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
						this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
						break;
					case 1:
						this.formData.userRealName1 = label
						this.formData.receiver1 = value
						if (Array.isArray(this.formData['hadUsers1'])) {
							this.formData['hadUsers1'] = this.formData['hadUsers1'].concat(selectUserList)
						} else {
							this.formData['hadUsers1'] = selectUserList
						}
						this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
						this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
						break;
					case 2:
						this.formData.userRealName2 = label
						this.formData.receiver2 = value
						if (Array.isArray(this.formData['hadUsers2'])) {
							this.formData['hadUsers2'] = this.formData['hadUsers2'].concat(selectUserList)
						} else {
							this.formData['hadUsers2'] = selectUserList
						}
						this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
						this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
						break;
				}
				this.$forceUpdate()
			},
			//删除已选用户
			handleCloseTag(index, type) {
				switch (type) {
					case 0:
						this.formData['hadUsers'].splice(index, 1)
						this.formData.userRealName = this.formData['hadUsers'].map(item => item.title).join(',')
						this.formData.receiver = this.formData['hadUsers'].map(item => item.key).join(',')
						break;
					case 1:
						this.formData['hadUsers1'].splice(index, 1)
						this.formData.userRealName1 = this.formData['hadUsers1'].map(item => item.title).join(',')
						this.formData.receiver1 = this.formData['hadUsers1'].map(item => item.key).join(',')
						break;
					case 2:
						this.formData['hadUsers2'].splice(index, 1)
						this.formData.userRealName2 = this.formData['hadUsers2'].map(item => item.title).join(',')
						this.formData.receiver2 = this.formData['hadUsers2'].map(item => item.key).join(',')
						break;
					case 3:
						this.formData['hadDeptList'].splice(index, 1)
						this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
						this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
						break;
				}
				this.$forceUpdate()
			},
			//回调时间
			handleConfirmTime(e) {
				console.log("handleConfirmTime", e)
				const {
					value
				} = e
				this.formData.send_time = value
				this.showTime = false
			},

			//选择部门
			handleTkiTreeDepart() {
				this.$refs.tkiTreeDepartRef._show()
			},
			//部门回调
			handleTkiTreeDepartConfirm(e) {
				let departmentSelected = []
				if (e && e.length) {
					departmentSelected = e
				}
				if (departmentSelected && departmentSelected.length) {
					const codes = this.formData['hadDeptList'].map(item => item.code)
					departmentSelected.forEach(item => {
						if (!codes.includes(item.code)) {
							this.formData['hadDeptList'].push(item)
						}
					})
				}
				this.formData.userRealName = this.formData['hadDeptList'].map(item => item.name).join(',')
				this.formData.receiver = this.formData['hadDeptList'].map(item => `dept@${item.code}`).join(',')
				this.$forceUpdate()

			},
			getDepartmentsData() {
				try {
					let params = {};
					postFormAction('/department/getDepartments', params).then((res) => {
						const {
							data
						} = res
						this.departmentList = data || [];
					});
				} catch (e) {
					console.error(e)
				} finally {}
			},

			handleRefresh() {
				this.init()
			},
			async handleSave() {
				this.$refs.form.validate(async valid => {
					if (valid) {
						try {
							this.formData.content = this.$refs.lEditorRef.content
							if (!this.formData.content) {
								uni.showToast({
									title: '请输入正文',
									icon: 'none'
								})
								return
							}
							const data = Object.assign({}, this.formData);
							delete data.hadUsers
							delete data.hadUsers1
							delete data.hadUsers2
							delete data.primaryKey
							delete data.hadDeptList
							delete data.attachments
							const fileList = this.$refs.fileUploadRef.fileList
							if (fileList && fileList.length) {
								data.attachments = fileList.map(item => item.id).join(',')
							}
							console.log('data', data);

							uni.showLoading({
								title: '加载中',
								mask: true
							});
							const res = await postFormAction(this.url.updateDraft, data);

							uni.showToast({
								title: res.msg,
								icon: 'none'
							})
							this.handleRefresh()
						} catch (error) {
							console.log('handleSave', error);
						} finally {
							uni.hideLoading()
						}
					} else {
						console.log('验证失败');
					}
				});
			},
			async handleSend() {
				this.$refs.form.validate(async valid => {
					if (valid) {
						try {
							this.formData.content = this.$refs.lEditorRef.content
							if (!this.formData.content) {
								uni.showToast({
									title: '请输入正文',
									icon: 'none'
								})
								return
							}
							const data = Object.assign({}, this.formData);
							delete data.hadUsers
							delete data.hadUsers1
							delete data.hadUsers2
							delete data.attachments
							delete data.primaryKey
							delete data.hadDeptList
							const fileList = this.$refs.fileUploadRef.fileList
							if (fileList && fileList.length) {
								data.attachments = fileList.map(item => item.id).join(',')
							}
							console.log('data', data);
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							await postFormAction(this.url.transmit, data);
							this.handleReturn()
						} catch (error) {
							console.log('handleSave', error);
						} finally {
							uni.hideLoading()
						}
					} else {
						console.log('验证失败');
					}
				});
			},
			//重新发送
			handleResetSend() {
				this.handleSend();
			},
			//撤回
			async handleWithdraw() {
				const that = this
				uni.showModal({
					title: "提示",
					content: "您确定撤回么？",
					success: async (res) => {
						if (res.confirm) {
							try {
								uni.showLoading({
									title: '删除中',
									mask: true
								});
								await postFormAction(that.url.recall, {
									id: that.mainId
								});
								this.handleReturn();
							} catch (e) {} finally {
								uni.hideLoading()
							}
						}
					}
				})
			},
			handleReturn() {
				var pages = getCurrentPages();
				// var currPage = pages[pages.length - 1]; //当前页面
				var prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.isDoRefresh = true
				uni.navigateBack()
			},
		}
	}
</script>

<style lang="less" scoped>
	.content {
		overflow-y: auto;

		&_form {
			padding: 20rpx 20rpx 0;
			margin-bottom: 800rpx;
		}
	}

	.body_bottom {
		position: fixed;
		z-index: 10;
		bottom: 0;
		height: 100rpx;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-around;
		gap: 20rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -2rpx 16rpx 0rpx rgba(0, 0, 0, 0.1);
	}
</style>